package servlet;

import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2022-03-11
 * Time:22:06
 */
@WebServlet("/blog_edit")
public class BlogEditServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.先判定是否登陆
//        2.从请求中读取 博客标题 和 博客正文 并且进行校验
//        3.创建一个Blog对象，并且插入到数据库中
//        4.跳转到博客列表页
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        User user = Util.checkLogin(req);

        if (user == null){
            //            如果当前未登录,就直接重定向到登录页面
            System.out.println("当前未登录不能访问博客详情页！");
            resp.sendRedirect("blog_login.html");
            return;
        }

        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if (title == null || "".equals(title) || content == null || "".equals(content)){
            System.out.println("标题或内容为空!");
            return;
        }

        BlogDao blogDao = new BlogDao();
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        blog.setPostTime(new Timestamp(System.currentTimeMillis()));
        blogDao.insert(blog);

        resp.sendRedirect("blog_list");
    }
}
